package com.wangxiaoxuan.seckill.controller;

import com.wangxiaoxuan.seckill.pojo.User;
import com.wangxiaoxuan.seckill.service.IGoodsService;
import com.wangxiaoxuan.seckill.service.IUserService;
import com.wangxiaoxuan.seckill.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @author 王小轩
 * @version 1.0
 * 商品
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IGoodsService goodsService;
    /**
     * 跳转商品页面
     * @return
     */
    @RequestMapping("/toList")
    public String toList(Model model,User user){
//        //cookie为跳转登录页面
//        if (StringUtils.isEmpty(ticket)){
//            return "login";
//        }
//        //通过cookie拿到user
//      // User user = (User) session.getAttribute(ticket);
//        User user = userService.getUserByCookie(ticket, request, response);
//        if (user == null){
//            //cookie为空重定向到登录页面
//            return "redirect:/login/toLogin";
//        }
//        //都没问题
        model.addAttribute("user",user);
        model.addAttribute("goodsList",goodsService.findGoodsVo());
        return "goodsList";
    }

    @RequestMapping("/toDetail/{goodsId}")
    public String toDetail(Model model,User user,@PathVariable Long goodsId){
        model.addAttribute("user",user);
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date nowDate = new Date();
        //秒杀状态
        int secKillStatus = 0;
        //秒杀倒计时
        int remainSeconds = 0;
        if (nowDate.before(startDate)){
            secKillStatus=0;
             remainSeconds = (int)((startDate.getTime() - nowDate.getTime()) / 1000);
        }else if (nowDate.after(endDate)){
            secKillStatus=2;
            remainSeconds=-1;
        }else {
            secKillStatus=1;
            remainSeconds=0;
        }
        model.addAttribute("remainSeconds",remainSeconds);
        model.addAttribute("secKillStatus",secKillStatus);
        model.addAttribute("goods",goodsVo);
        return "goodsDetail";
    }
}
